# coding=utf-8
from core.sqlite3db.SqliteInner import SqliteInner
from core.sqlite3db.SqliteSql import SqliteSql
from core.users import Users
from tools import convert, md5
from tools.OperationError import OperationError
from tools.httpdoer import Request
from webapp.config import Config


class Login:
    def login(self, name, password, storeID, isUsername='N', isPassword='N'):

        try:
            request = Request(Config.ERP_URL + "api/pos/login")
            request.method = "post"  # 调用 _set_method
            request.timeout = 10  # 调用 _set_timeout
            request.path_params = None
            request.query = {"NAME": name, "PASSWORD": password, "CP_C_STORE_ID": storeID}
            r = request.send(json=False)
            if r is None:
                raise OperationError(-1, "服务端没有返回数据")
            else:
                self.setInfo(r, name, password, isUsername, isPassword)
        except Exception as e:
            # 在线报错是否抛出，由后期设计决定，暂时不抛出
            if type(e) != OperationError:
                raise e

        # 离线验证
        res = self.loginlocal(name, password, storeID)

        return res

    def setInfo(self, response, name, password, isUsername='N', isPassword='N'):

        print(response.text)

        if response.status_code != 200:
            raise OperationError(-1, response.text)

        if response.json == None:
            raise OperationError(-1, "服务器返回格式错误")

        res = convert.to_dict(response.json)
        if res["code"] != 0:
            raise OperationError(-1, res["message"])

        data = res.get("data", None)
        if data is None:
            raise OperationError(-1, "服务器返回data为空")

        # 是否记住账号密码
        users = Users()
        users.saveUserRemInfo(name, password, isUsername, isPassword)
        # 保存到数据库
        self.saveInfo(res["data"])


    def saveInfo(self, data):
        # 保存到数据库
        print(data)
        sqliteinit = SqliteInner()
        try:
            sqliteinit.setConnetion("master")
            ID = data.get("ID", None)
            ECODE = data.get("ECODE", None)
            PASSWORD = data.get("SIGNKEY", None)
            ENAME = data.get("ENAME", None)
            CP_C_STORE_ID = data.get("CP_C_STORE_ID", None)
            CP_C_DISTRIB_ID = data.get("CP_C_DISTRIB_ID", None)
            # 新增
            sqliteinit.execute(str(SqliteSql.insertUsers),
                               (ID, ECODE, PASSWORD, ENAME, CP_C_STORE_ID, CP_C_DISTRIB_ID))
        except Exception as e:
            raise e
        finally:
            sqliteinit.closedb()


    def loginlocal(self, name, password, storeID):
        # 本地登录
        sqliteinit = SqliteInner()
        try:
            sqliteinit.setConnetion("master")
            list = sqliteinit.execute_list(str(SqliteSql.usersLogin % (name, password, storeID)))
            if list != None and len(list) > 0:
                res = list[0]
            else:
                raise OperationError(-1, "账号或密码错误！")
        except Exception as e:
            raise e
        finally:
            sqliteinit.closedb()

        return res


if __name__ == "__main__":
    login = Login()
    password = md5.genearteMD5("FCPOS01")
    print(len(password))
    r = login.login("FCPOS01", password, 206598864952, 'Y', 'Y')
    print(r)
